﻿using NcOpcuaClientSDK;
using Newtonsoft.Json.Linq;
using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mes_app_control
{

    public partial class Control_commd_diao_Form : Form
    {
        private NcOpcuaClient m_OpcUaClient;
        int parent_id;
        private ControlCommandDal controlCommandDal = new ControlCommandDal();
        public Control_commd_diao_Form(int parent_id)
        {
            InitializeComponent();
            this.parent_id = parent_id;
            this.Load += Control_commd_diao_Form_Load;
        }

        public class SubListener : NcOpcuaSubListener
        {

            public Control_commd_diao_Form from = null;
            public override void Receiver(string param, string value)
            {
                if (from != null)
                {
                    from.listBoxSubValues.Invoke(new Action(() =>
                    {
                        from.listBoxSubValues.Items.Insert(0, $"{param}：{value}");
                    }
                    ));

                }
            }

            public override void Receiver(string pname_, object pvalue_)
            {
            }
        }



        void Query(int parent_id)
        {
            ControlCommand controlCommand = controlCommandDal.Get(parent_id);
            TextBox_machine_no.Text = controlCommand.machine_no;
            TextBox_machine_name.Text = controlCommand.machine_name;
            TextBox_machine_address.Text = controlCommand.machine_address;
            TextBox_command_param.Text = controlCommand.command_param;
            ComboBox_supplier_no.Text = controlCommand.supplier_no;
            TextBox_command_value.Text = controlCommand.command_value;
            TextBox_description.Text = controlCommand.description;

        }




        private void Button_save_Click(object sender, EventArgs e)
        {
        if (parent_id == 0)
        { 
        if (controlCommandDal.Add(new ControlCommand()
        {
            machine_no = TextBox_machine_no.Text,
            machine_name = TextBox_machine_name.Text,
            machine_address = TextBox_machine_address.Text,
            command_param = TextBox_command_param.Text,
            supplier_no = ComboBox_supplier_no.Text,
            command_value = TextBox_command_value.Text,
            description = TextBox_description.Text
        }) > 0)
        {
            MessageBox.Show("保存成功");
 
        }
        else
        {
            MessageBox.Show("保存失败");
        }
        }else
        if (controlCommandDal.Update(new ControlCommand()
        {
            id = parent_id,
            machine_no = TextBox_machine_no.Text,
            machine_name = TextBox_machine_name.Text,
            machine_address = TextBox_machine_address.Text,
            command_param = TextBox_command_param.Text,
            supplier_no = ComboBox_supplier_no.Text,
            command_value = TextBox_command_value.Text,
            description = TextBox_description.Text
        }) > 0)
        {
            MessageBox.Show("保存成功");
            this.Close();
        }
        else
        {
            MessageBox.Show("保存失败");
        }
        }

        private void Btn_Connect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.TextBox_machine_address.Text))
            {
                this.TextBox_machine_address.Focus();
                MessageBox.Show("请先设置服务地址。");
            }
            try
            {
                string address = this.TextBox_machine_address.Text;
                // 添加日志输出
                Console.WriteLine($"尝试连接地址: {address}");
                var _connect = m_OpcUaClient.Connect(address);
                if (_connect)
                {
                    MessageBox.Show("连接成功！");
                }
                else
                {
                    MessageBox.Show("连接失败！");
                }
            }
            catch (Exception ex)
            {
                // 输出详细错误信息
                MessageBox.Show($"连接异常: {ex.Message}\n{ex.StackTrace}");
            }
 
        }

        private void Button_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Control_commd_diao_Form_Load(object sender, EventArgs e)
        {
            this.Width = 600;
            this.Height = 500;

            this.m_OpcUaClient = new NcOpcuaClient();
            var subListener = new SubListener();
            subListener.from = this;
            this.m_OpcUaClient.AddNcSubListener(subListener);

            Query(parent_id);
            /*
            try
            {
                this.m_OpcUaClient = new NcOpcuaClient();
                var subListener2 = new SubListener();
                subListener.from = this;
                this.m_OpcUaClient.AddNcSubListener(subListener2);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"SDK 初始化失败: {ex.Message}");
            }
            */

        }

        private void Btn_exec_Click(object sender, EventArgs e)
        {
            List<object> items = new List<object>();
            string _param = this.TextBox_command_param.Text;
            string _value = this.TextBox_command_value.Text;
            var _changemode = new KeyValueItem { key = _param, value = _value };
            items.Add(_changemode);
            try
            {
                JObject jo = m_OpcUaClient.SetNcParams(items);
                if ((bool)jo["Result"])
                {
                    MessageBox.Show("修改成功！");
                }
                else
                {
                    MessageBox.Show("修改失败！" + jo["ErrorInfo"]);
                }
            }
            catch (Exception ex)
            {
                var temp = ex.ToString();
            }
        }

        /// <summary>
        /// 从主页面发起连接并执行命令的方法
        /// </summary>
        /// <param name="machineAddress">机器地址</param>
        /// <param name="commandParam">命令参数</param>
        /// <param name="commandValue">命令值</param>
        /// <returns>操作是否成功</returns>
        public bool ConnectAndExecuteCommand(string machineAddress, string commandParam, string commandValue)
        {
            if (string.IsNullOrEmpty(machineAddress) ||
                string.IsNullOrEmpty(commandParam) ||
                string.IsNullOrEmpty(commandValue))
            {
                return false;
            }

            NcOpcuaClient opcClient = null;
            try
            {
                // 创建新的客户端实例
                opcClient = new NcOpcuaClient();

                // 建立连接
                var isConnected = opcClient.Connect(machineAddress);
                if (!isConnected)
                {
                    return false;
                }

                // 执行命令
                List<object> items = new List<object>();
                var command = new KeyValueItem { key = commandParam, value = commandValue };
                items.Add(command);

                JObject result = opcClient.SetNcParams(items);
                return (bool)result["Result"];
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ConnectAndExecuteCommand 异常: {ex.Message}");
                return false;
            }
            finally
            {
                // 清理资源
                opcClient = null;
            }

        }


    }
}
